/** 
 * 2011-10-10 下午05:49:58 
 * UdpProtocolEncoder.java 
 * author:sunb 
 */
package com.u6.udp.netty;

import static org.jboss.netty.channel.Channels.write;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelDownstreamHandler;

/**
 * @author sunbin
 * 
 */
public class UdpProtocolEncoder extends SimpleChannelDownstreamHandler  {

	public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
		if (!(evt instanceof MessageEvent)) {
			ctx.sendDownstream(evt);
			return;
		}

		MessageEvent e = (MessageEvent) evt;
		Object msg = e.getMessage();
		if (!(msg instanceof UdpMessage)) {
			return;
		}
		byte[] bytes = UdpMessageEncoder.encode((UdpMessage) e.getMessage());
		final ChannelBuffer buf = ChannelBuffers.wrappedBuffer(bytes);
		ChannelFuture future = e.getFuture();

		write(ctx, future, buf, e.getRemoteAddress());

	}

	/*@Override
	public void encode(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		Object msg = e.getMessage();
		if (!(msg instanceof UdpMessage)) {
			return;
		}
		byte[] bytes = UdpMessageEncoder.encode((UdpMessage) e.getMessage());
		final ChannelBuffer buf = ChannelBuffers.wrappedBuffer(bytes);
		ChannelFuture future = e.getFuture();
		Channels.write(ctx, future, buf);

	}*/

	/*
	 * @Override public void writeRequested(ChannelHandlerContext ctx,
	 * MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg
	 * instanceof UdpMessage)) { return; } byte[] bytes =
	 * UdpMessageEncoder.encode((UdpMessage) e.getMessage()); final
	 * ChannelBuffer buf = ChannelBuffers.wrappedBuffer(bytes); ChannelFuture
	 * future = e.getFuture(); Channels.write(ctx, future, buf);
	 * 
	 * }
	 */
}
